import mysql.connector
import uuid
import time


def connect_to_database():
    """连接到MySQL数据库"""
    try:
        connection = mysql.connector.connect(
            host='47.96.41.254',
            user='root',
            password='Y4AnLTX123',
            database='info_island',
            charset='utf8'
        )
        return connection
    except mysql.connector.Error as err:
        print(f"数据库连接错误: {err}")
        return None


def insert_news_data(data):
    """将爬取的数据插入到数据库中"""
    # 生成一个新的UUID作为id

    connection = connect_to_database()
    if connection is None:
        return

    try:
        cursor = connection.cursor()
        # 使用INSERT IGNORE语句进行去重插入
        insert_query = (
            "INSERT IGNORE INTO news (id, title, description, content_url, category_id,"
            " is_published, view_num, published_at, favorite_num, like_num, status, user_unique_id, cover_image) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        )
        cursor.execute(insert_query, (
            data['id'], data['title'], data['description'], data['contentUrl'], data['categoryId'],
            1, 0, time.strftime('%Y-%m-%d %H:%M:%S'),
            0, 0, 0, 'ISLAND_17439220b022', data['coverImage']
        ))
        # 当前时间
        connection.commit()
        print("数据插入成功!")
    except mysql.connector.Error as err:
        print(f"数据插入错误: {err}")
    finally:
        cursor.close()
        connection.close()